import { NextRequest, NextResponse } from 'next/server';
import { promises as fs } from 'fs';
import path from 'path';
import matter from 'gray-matter';

// export const dynamic = 'force-static';

// 从 markdown 文件读取博客数据的函数
async function getBlogPosts() {
  try {
    const markdownDir = path.join(process.cwd(), 'markdown');
    const files = await fs.readdir(markdownDir);
    const mdFiles = files.filter(file => file.endsWith('.md'));
    
    const posts = await Promise.all(
      mdFiles.map(async (file, index) => {
        const filePath = path.join(markdownDir, file);
        const fileContent = await fs.readFile(filePath, 'utf8');
        const { data } = matter(fileContent);
        
        return {
          id: index + 1,
          title: data.title || '',
          excerpt: data.excerpt || '',
          date: data.date || '',
          slug: data.slug || file.replace('.md', ''),
          category: data.category || '未分类',
          readTime: data.readTime || '5 分钟',
          content: fileContent // 包含完整内容，可根据需要返回
        };
      })
    );
    
    return posts.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  } catch (error) {
    console.error('Error reading markdown files:', error);
    return [];
  }
}

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const category = searchParams.get('category');
  const limit = searchParams.get('limit');

  // 从 markdown 文件读取博客数据
  const blogPosts = await getBlogPosts();
  let filteredPosts = blogPosts;

  // 按分类筛选
  if (category) {
    filteredPosts = filteredPosts.filter(post => 
      post.category.toLowerCase() === category.toLowerCase()
    );
  }

  // 限制返回数量
  if (limit) {
    const limitNum = parseInt(limit, 10);
    if (!isNaN(limitNum) && limitNum > 0) {
      filteredPosts = filteredPosts.slice(0, limitNum);
    }
  }

  // 模拟 API 延迟
  await new Promise(resolve => setTimeout(resolve, 100));

  return NextResponse.json({
    success: true,
    data: filteredPosts,
    count: filteredPosts.length,
    total: blogPosts.length
  });
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    // 验证必要字段
    if (!body.title || !body.excerpt) {
      return NextResponse.json(
        { success: false, error: "标题和摘要是必填字段" },
        { status: 400 }
      );
    }

    // 获取现有文章数量
    const existingPosts = await getBlogPosts();
    
    // 创建新文章数据
    const newPost = {
      id: existingPosts.length + 1,
      title: body.title,
      excerpt: body.excerpt,
      date: new Date().toISOString().split('T')[0],
      slug: body.title.toLowerCase().replace(/\s+/g, '-').replace(/[^\w\-]+/g, ''),
      category: body.category || "未分类",
      readTime: body.readTime || "5 分钟"
    };

    // 创建 markdown 文件内容
    const frontmatter = `---
title: "${newPost.title}"
excerpt: "${newPost.excerpt}"
date: "${newPost.date}"
slug: "${newPost.slug}"
category: "${newPost.category}"
readTime: "${newPost.readTime}"
---

# ${newPost.title}

${body.content || newPost.excerpt}

<!-- 这里可以添加更多内容 -->
`;

    // 保存 markdown 文件
    const markdownDir = path.join(process.cwd(), 'markdown');
    const fileName = `${newPost.slug}.md`;
    const filePath = path.join(markdownDir, fileName);
    
    await fs.writeFile(filePath, frontmatter, 'utf8');

    // 模拟 API 延迟
    await new Promise(resolve => setTimeout(resolve, 200));

    return NextResponse.json({
      success: true,
      data: newPost,
      message: "文章创建成功"
    }, { status: 201 });

  } catch (error) {
    console.error('Error creating post:', error);
    return NextResponse.json(
      { success: false, error: "请求格式错误" },
      { status: 400 }
    );
  }
}
